<?php
namespace services\core;

use Yii;
use models\FunctionMenu;
use heihei\base\UserHintExitException;
use heihei\helpers\TreeStructHelper;
/**
 * 用户管理
 *
 * @author dejin <ldj@hianto2o.com>
 */
class FunctionMenuService extends \services\Service
{
   public $platformCode = '';

   public function getMenuTree($parentId = 0, $isAll = false){
      $menuQuery = FunctionMenu::find()->indexBy('id')->asArray();
      if(!$isAll){
         $menuQuery->andWhere(['status'=>'enable']);
      }
      $menuList = $menuQuery->all();
      if($parentId > 0 && !isset($menuList[$parentId])){
         return [];
      }
      
      $menuTree = TreeStructHelper::toTree($menuList, [
         'parentValue' => $parentId
      ]);
      
      return array_values($menuTree);
   }

   public function getItem($id){
      return FunctionMenu::findOne($id);
   }

   public function save($data, $id = null){
      if($id){
         $item = FunctionMenu::findOne($id);
      }
      else{
         $item = new FunctionMenu();
      }

      if(!$item){
         throw new UserHintExitException("id:{$id}未找到!");
      }

      $item->load($data, '');

      return $item->save();
   }

   public function getDelete($id){
      $item = $id ? FunctionMenu::findOne($id) : null;
      if(!$item){
         throw new UserHintExitException("id:{$id}未找到!");
      }

      $exsitChild = FunctionMenu::find()->where(['parent_id' => $id])->scalar();
      if($exsitChild){
         throw new UserHintExitException("\"{$item->name}\"还有子项不能删除!");
      }
      return $item->delete();
   }
}
